//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.shangcheng.interceptor;

import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.shangcheng.common.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Value("${jwt.secretkey}")
    private String secret;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        Result<String> ret = Result.fail("没有权限");
        response.setContentType("application/json;charset=utf-8");
        if (null != token && !"".equals(token)) {
            if (!JWTUtil.verify(token, this.secret.getBytes())) {
                ret.setCode(10002);
                ret.setMessage("身份信息非法");
                response.getWriter().write(JSONUtil.toJsonStr(ret));
                return false;
            } else {
                JWT jwt = JWTUtil.parseToken(token);
                long expTime = Long.parseLong(jwt.getPayload("exp").toString());
                System.out.println("过期时间：" + expTime);
                long now = System.currentTimeMillis();
                System.out.println("当前时间：" + now);
                if (expTime < now) {
                    ret.setCode(10003);
                    ret.setMessage("登陆超时");
                    response.getWriter().write(JSONUtil.toJsonStr(ret));
                    return false;
                } else {
                    return true;
                }
            }
        } else {
            ret.setCode(10001);
            ret.setMessage("未登录");
            response.getWriter().write(JSONUtil.toJsonStr(ret));
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}